var express = require('express');

// 配置
var config = require('../wechat/config').wechat;
// 微信sdk
var wechat = require('wechat');

var request = require("request");
const router = require('koa-router')();
// 接口配置信息
const validateToken = require("../wechat/validateToken");

// 解析
const getRawBody = require('raw-body')
const xml2js = require('xml2js')

// 数据库相关
const util = require("../common/utils")

const { sequelize } = require('../common/dbs')
const wxModel = require("../models/wx_user")
const wxinfo = wxModel(sequelize);
const codeModel = require("../models/wx_code")
const codeinfo = codeModel(sequelize);
// md5 token校验
let jwt = require('jsonwebtoken');
var md5 = require('md5-node');

// 消息
const msgTemplate = require("../wechat/messageTemplate");

// 菜单 
var btn = {
	"button": [{  //一级菜单
		"type": "click",
		"name": "一键登录",
		"key": "V1001_LOGIN"
	},
	]
}

router.get('/', async (ctx) => {
	// 微信校验 接口配置信息
	validateToken(ctx).then((t) => {
		ctx.body = t
	});
	await next()
})
router.post('/', async (ctx, next) => {
	var data = await getRawBody(ctx.req, {
		length: ctx.length,
		limit: '1mb',
		encoding: ctx.charset,
	})
	const xml = await parseXMLAsync(data)
	const msgType = xml.xml.MsgType[0]
	const toUserName = xml.xml.ToUserName[0]
	const toFromName = xml.xml.FromUserName[0]
	const event = xml.xml.Event ? xml.xml.Event[0] : ''
	const content = xml.xml.Content ? xml.xml.Content[0] : '你说卅？'
	let _this = ctx
	var vToken = ''
	console.log(xml.xml)
	// 获取token
	function getToken(canback) {
		// 1.1获取access_token
		request({
			timeout: 5000, // 设置超时
			method: 'GET', //请求方式
			url: config.url+'/token',
			qs: { //参数，注意get和post的参数设置不一样 
				grant_type: "client_credential",
				appid: config.appid,
				secret: config.appsecret
			}
		},
			function (error, response, body) {
				if (!error && response.statusCode == 200) {
					body = JSON.parse(body);
					if (body.access_token) {
						var token = body.access_token;
						canback(token)
					} else {
						canback('')
					}
				} else {
					canback('')
				}
			});
	}
	// 获取token 创建导航
	function createMenu() {
		getToken(token => {
			setItem(token)
		})
		// // 1.3加载自定义菜单 ，非个人主体公众号才有此权限。个人主体可用测帐号的appid，secret来实现自定义菜单。
		function setItem(token) {
			request({
				timeout: 5000, // 设置超时
				method: 'POST', //请求方式
				url: config.url+'/menu/create?access_token=' + token,
				headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
				form: JSON.stringify(btn)
			},
				function (error, response, body) {
					if (!error && response.statusCode == 200) {
						console.log('body', body);
					} else {
						console.log("error");
					}
				}
			)
		}
	}
	// 创建用户
	function createUser() {
		getUserInfo(toFromName)
		// 获取基本信息
		async function getUserInfo(openid) {
			// 判断是否存在
			let wxUser = await wxinfo.findOne(
				{
					where: {
						openid: openid
					},
				}
			);
			// 不存在就创建
			if (wxUser) {
			} else {
				getToken(token => {
					createWxUser(token, openid)
				})

			}
			return
		}
		// 注册用户
		function createWxUser(token, openid) {
			request({
				timeout: 5000, // 设置超时
				method: 'POST', //请求方式
				url: config.url+'/user/info?access_token=' + token + '&openid=' + openid + '&lang=zh_CN',
				headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
			},
				function (error, response, body) {
					if (!error && response.statusCode == 200) {
						// 存在即编辑

						let data = JSON.parse(body)
						// 新增用户
						data['_id'] = openid
						wxinfo.create(data).then(requestData => {
							if (requestData.dataValues) {
								ctx.body = util.resultSuccess({ message: '添加成功', data: requestData.dataValues });
							} else {
								ctx.body = util.resultSuccess({ code: 0, message: '添加失败', data: null });
							}
						})
						console.log('user', body);
					} else {
						console.log("error");
					}
				}
			)
		}

	}

	// 存验证码
	function createCode(code, toFromName, toUserName, canbank) {

		// 判断验证码是否存在
		codeinfo.findOne(
			{
				where: {
					openid: toFromName
				},
			}
		).then(codeData => {
			if (!codeData) {
				codeinfo.create({
					codeid: getuuid(36),
					code: code,
					openid: toFromName,
					timer: Date.parse(new Date())
				}).then(requestData => {

				})
			} else {
				codeinfo.update({
					code: code,
					timer: Date.parse(new Date())
				}, {
					where: {
						openid: toFromName,
					}
				})
			}
		})
	}

	messageProcessing()
	// 消息处理
	function messageProcessing() {
		// 接收到文本消息
		var msgdata = {}
		if (msgType == 'text') {
			msgdata = {
				FromUserName: toFromName,
				ToUserName: toUserName,
				reply: `${content}`,
			};
			ctx.body = msgTemplate.textMessage(msgdata)
			return
		}
		if (msgType == 'event') {
			if (event == 'CLICK') {
				// 创建用户
				createUser()
				// 发送验证码
				sendCode('click')
			} else {
				//关注
				if (event == 'subscribe') {
					// 创建菜单
					createMenu()
					// 创建用户
					createUser()
					// 发送验证码
					sendCode('subscribe')
				}
			}
		}

		if (msgType == 'image') {
			msgdata = {
				FromUserName: toFromName,
				ToUserName: toUserName,
				reply: `${content}`,
			};
			ctx.body = msgTemplate.imageMessage(msgdata)
		}

		// 发送验证码
		function sendCode(type) {
			let code = getuuid(6)
			createCode(code, toFromName, toUserName)
			let msg = type == 'click' ? ('验证码：' + code + '\n请在10分钟内登录[吃瓜]') : ('感谢关注导航站\n' + '验证码：' + code + '\n请在10分钟内登录[吃瓜]')
			var msgdata = {
				FromUserName: toFromName,
				ToUserName: toUserName,
				reply: msg
			};
			ctx.body = msgTemplate.textMessage(msgdata)
		}
	}

	return

})



// 输入验证码登录
router.post('/wxLogin', async (ctx) => {
	try {
		ctx
			.validateBody("code")
			.required("验证码不能为空")
			.isString()
			.trim()

		let reqBody = ctx.request.body;
		// 查询验证码是否存在
		let cardData = await codeinfo.findOne(
			{
				where: {
					code: reqBody.code
				}
			}
		);
		if (!cardData) {
			// console.log(Date.parse(cardData.timer),Date.parse(new Date()))
			ctx.body = util.resultError({ code: 0, message: '验证码错误', data: '' });
			return
		} else {
			let timer = Date.parse(new Date()) - Date.parse(cardData.timer)
			if (timer / 1000 / 60 < 10) {
					let payload = {
						"code": md5(cardData.code),
						"openid": md5(cardData.openid)
					}
					let newToken = jwt.sign(payload, 'itliuyang', { expiresIn: 60000 });

					let updateInfo = await wxinfo.update({
						token: newToken
					}, {
						where: {
							openid: cardData.openid
						}
					})
					if (updateInfo) {
						ctx.body = util.resultSuccess({
							message: '登录成功', data: {
								token: newToken
							}
						});
					} else {
						ctx.body = util.resultError({ code: 0, message: '登录失败，请稍后再试', data: null })
					}

			} else {
				ctx.body = util.resultError({ code: 0, message: '验证码超时，请重新获取', data: '' });
			}

		}
		// // 加盐
		// if (md5(reqBody.pwd + cardData.pwdsalt) == cardData.userpwd) {
		// 	let payload = {
		// 		"name": md5(cardData.username),
		// 		"userid": md5(cardData.id)
		// 	}
		// 	let newToken = jwt.sign(payload, 'itliuyang', { expiresIn: 60000 });
		// 	console.log(newToken);
		// 	let updateInfo = await userinfo.update({
		// 		token: newToken
		// 	}, {
		// 		where: {
		// 			id: cardData.id
		// 		}
		// 	})
		// 	if (updateInfo) {
		// 		ctx.body = util.resultSuccess({
		// 			message: '登录成功', data: {
		// 				token: newToken
		// 			}
		// 		});
		// 	} else {
		// 		ctx.body = util.resultError({ code: 0, message: '登录失败，请稍后再试', data: null })
		// 	}

		// } else {
		// 	ctx.body = util.resultError({ code: 0, message: '登录失败，账号或者密码错误', data: null });
		// }
	} catch (err) {
		console.log(err);
		ctx.body = util.resultError({ code: 0, message: err.message, data: null });
	}
})



// 解析xml
function parseXMLAsync(xml) {
	return new Promise((resolve, reject) => {
		xml2js.parseString(xml, { trim: true }, function (err, content) {
			if (err) {
				reject(err)
			}
			resolve(content)
		})
	})
}
// 获取随机id
function getuuid(number = 36) {
	let s = [];
	let hexDigits = "0123456789abcdef";
	for (var i = 0; i < number; i++) {
		s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
	}
	if (number > 14) {
		s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
		s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
	}
	// s[8] = s[13] = s[18] = s[23] = "-";
	var uuid = s.join("");
	return uuid;
}
module.exports = router.routes();

